package com.huafv.reggie.controller;

import com.huafv.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.filePath}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        log.info("文件上传，文件名: {} ", originalFilename);

        if (StringUtils.isNotEmpty(originalFilename)) {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String fileName = UUID.randomUUID() + suffix;

            // 判断目录是否存在，不存在则创建
            File DIR = new File(basePath);
            if(!DIR.exists()) {
                DIR.mkdirs();
            }
            // 将文件转存到指定目录
            try {
                file.transferTo(new File(basePath + fileName));
            } catch (IOException e) {
                log.error(e.getMessage());
                return R.error("未知错误");
            }
            return R.success(fileName);

        }else{
            return R.error("上传文件失败");
        }

    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            // 输入流读取文件
            FileInputStream fileInputStream = new FileInputStream(basePath + name);

            // 输出流输出文件
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            // 传输
            int len = 0;
            byte[] buff = new byte[1204];
            while( (len = fileInputStream.read(buff)) != -1){
                outputStream.write(buff, 0, len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }
}
